package com.my.geteway.filter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/*
自定义全局过滤器
*   GlobalFilter : 需要重写 filter 方法，在其中实现自己的处理逻辑，很大部分都是对 exchange 进行操作，取值赋值等等
    Ordered ： 需要重写 getOrder 方法，决定自定义 filter 在链中的位置，按照数字大小进行的排序
* */
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    private static final Log log = LogFactory.getLog(MyGlobalFilter.class);
    private static final String START_STAMP = "startStamp";

    /**
     * 请求响应时长统计
     * 1.首先将请求进来时的时间戳写入到 exchange中
     * 2.filter链走完后，无论成功或者失败，都视为完成，从exchange取出开始时间戳，打印时长信息
     * @param exchange the current server exchange
     * @param chain provides a way to delegate to the next filter
     * @return mono
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("全局自定义过滤器");

//        String token = exchange.getRequest().getQueryParams().getFirst("token");
//        if (token == null || token.isEmpty()) {
//            logger.info( "token is empty..." );
//            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//            return exchange.getResponse().setComplete();
//        }
//        return chain.filter(exchange);

        exchange.getAttributes().put(START_STAMP, System.currentTimeMillis());
        return chain.filter(exchange)
                .doFinally(f -> printDurationTime(exchange));
    }

    private void printDurationTime(ServerWebExchange exchange) {
        long startStamp = exchange.getAttribute(START_STAMP);
        long endStamp = System.currentTimeMillis();
        log.info("全局自定义过滤器 time : " + (endStamp - startStamp) + " ms");
    }

    /**
     * @return order
     */
    @Override
    public int getOrder() {
        return 0;
    }

}
